<template>
  <!-- 话题部分 -->
  <div class="topics">
    <div class="topics-scroll-container">
      <template v-for="(row, rowIndex) in allTopics" :key="rowIndex">
        <div class="topic-row">
          <template v-for="(item, index) in row" :key="index">
            <!-- {{ item }} -->
            <div class="topic" @click="goToTopic(item.id)">
              <van-icon :name="item.icon" v-if="!item.isViewMore"></van-icon>
              <span class="name">{{ item.name }}</span>
            </div>
          </template>
        </div>
      </template>
    </div>
  </div>

  <!-- 笔记列表  -->
  <van-list
    class="notes-list"
    v-model:loading="loading"
    :immediate-check="true"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :scrollable-container="getScrollContainer"
  >
    <ul class="list">
      <li
        class="list-item"
        v-for="(note, index) in notes"
        :key="index"
        :id="note.note.id"
        @click="goToDetail(note.note.id)"
      >
        <div class="cover">
          <template v-if="note.note.video_cover && note.note.video_url">
            <video class="thumbnail" muted :poster="note.note.video_cover">
              <source :src="note.note.video_url" type="video/mp4" />
            </video>
            <van-icon name="play-circle" class="play-circle" />
          </template>
          <template v-if="note.note.images && note.note.images.length > 1">
            <img :src="proxyImageUrl(note.note.image_u)" class="thumbnail" />
            <van-icon name="photograph" class="photograph" />
          </template>
          <template v-else>
            <img :src="proxyImageUrl(note.note.image_u)" class="thumbnail" />
          </template>
        </div>
        <div class="title">{{ note.note.title }}</div>

        <div class="author-like">
          <div class="author">
            <img :src="note.note.author.p" class="avatar" />
            {{ note.note.author.n }}
          </div>
          <div class="like"><van-icon name="like-o" />{{ note.note.like_count }}</div>
        </div>
      </li>
    </ul>
  </van-list>
</template>

<script setup>
import { fetchNoteList } from '@/api/index.js'
import { ref, computed, onMounted } from 'vue'

import { proxyImageUrl } from '@/tool/index.js'

import { useRouter } from 'vue-router'
const router = useRouter()

const loading = ref(true)
const finished = ref(false)

const pageNumber = ref(1)
const limit = ref(20)
const offset = computed(() => {
  return (pageNumber.value - 1) * limit.value
})

const currentResponseLength = ref(0)
const notes = ref([])
const topics = ref([])

const allTopics = computed(() => {
  return topics.value.map((row) =>
    row.map((item) => ({
      ...item,
      isViewMore: item.name === '查看更多',
    })),
  )
})

const isInit = ref(true)

onMounted(() => {
  initLoad(offset.value, limit.value, isInit.value)
})

// 初始化加载
const initLoad = async (offset, limit, isInit) => {
  await getNoteList(offset, limit, isInit)
}

const onLoad = async () => {
  if (finished.value) {
    loading.value = false
    return
  }
  pageNumber.value++
  isInit.value = false
  await getNoteList(offset.value, limit.value, isInit.value)
}
// 笔记列表
const getNoteList = async (offset, limit, isInit) => {
  try {
    loading.value = true

    const { state, result } = await fetchNoteList(offset, limit)

    if (state === 'success') {
      currentResponseLength.value = result.list.length

      if (currentResponseLength.value > 0) {
        // 如果是初始化加载
        if (isInit) {
          notes.value = result.list
          topics.value = result.topics
        } else {
          notes.value = [...notes.value, ...result.list]
        }
      } else {
        finished.value = true
      }
    } else {
      // 如果请求失败，回退页码
      console.log('请求fail，回退页码')
      pageNumber.value--
      loading.value = false
    }
  } catch (error) {
    console.log('获取笔记列表错误:', error)
    pageNumber.value--
  } finally {
    loading.value = false
  }
}
// 笔记详情页
const goToDetail = (id) => {
  router.push({ path: `/note/${id}` })
}
// 话题活动页
const goToTopic = (id) => {
  router.push({ path: `/topic/${id}` })
}
</script>

<style scoped lang="scss">
.topics {
  padding: 10px;
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
  }

  .topics-scroll-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
    min-width: 100%;
    padding: 0 10px;
  }

  .topic-row {
    display: flex;
    gap: 10px;
    align-items: center;
    flex-wrap: nowrap;
    width: 100%;
  }

  .topic {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background-color: #f3f8fb;
    border: 1px solid #e0e0e0;
    border-radius: 16px;
    padding: 5px 12px;
    font-size: 13px;
    color: #53969d;
    text-align: center;
    white-space: nowrap;
    cursor: pointer;
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #e6f7ff;
    }
  }

  .topic.view-more {
    // background-color: transparent;
    // border: none;
    // color: #409eff;
    // font-weight: normal;
    // cursor: pointer;
    // transition: color 0.2s ease;

    // &:hover {
    //   color: #1a80ff;
    // }
  }
}

.notes-list {
  min-height: 100vh;

  :deep(.van-list__finished-text) {
    padding-bottom: 50px; // 避免被底部TabBar遮挡
  }

  .list {
    list-style: none;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    row-gap: 20px;
    column-gap: 10px;
    padding: 10px;

    .list-item {
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      display: flex;
      flex-direction: column;
      height: 100%;

      .cover {
        position: relative;
        width: 100%;
        // padding-bottom: 133.33%; // 3:4 宽高比
        aspect-ratio: 3 / 4;

        .thumbnail {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          border-top-left-radius: 10px;
          border-top-right-radius: 10px;
          object-fit: cover;
        }

        .play-circle {
          position: absolute;
          top: 10px;
          right: 5px;
          filter: invert(0.6);
          z-index: 2;
        }

        .photograph {
          position: absolute;
          top: 10px;
          right: 5px;
          filter: invert(0.3);
          z-index: 2;
        }
      }

      .title {
        // 标题最多显示两行
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 14px;
        margin-bottom: 10px;
      }

      .author-like {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .author {
          font-size: 12px;
          color: #999;
          display: flex;
          align-items: center;

          .avatar {
            // 头像 设置为圆形
            border-radius: 50%;
            width: 20px;
            height: 20px;
            object-fit: cover;
            margin-right: 5px;
          }
        }

        .like {
          font-size: 14px;
          color: #333;

          .van-icon {
            margin-right: 5px;
          }
        }
      }
    }
  }
}
</style>
